//
//  YBTabBarController.m
//  WaWaJiClient
//
//  Created by Rookie on 2017/11/15.
//  Copyright © 2017年 zego. All rights reserved.
//

#import "YBTabBarController.h"
#import "YBTabBar.h"

//#import "MyFollowViewController.h"
#import "NearbyVC.h"
#import "myVideoV.h"
#import "YBHomeViewController.h"
#import "YBCenterVC.h"
#import "TCVideoRecordViewController.h"
#import "TCVideoPublishController.h"
#import "YBLiveOrVideo.h"
#import "PubH5.h"
#import "YBShareView.h"
#import "YBUserAuthVC.h"
#import "YBMsgC2CListVC.h"
#import "WYTCityPageVC.h"

@interface YBTabBarController ()<YBTabBarDelegate,UITabBarControllerDelegate,V2TIMConversationListener,RTabBarDelegate>
{
    YBHomeViewController*_homeVC;
    
    NSMutableArray *navArr;
}
@property (nonatomic, strong) NSDate *lastSelectedDate;

@property(nonatomic,strong)NSDate *cityLastDate;

@end

@implementation YBTabBarController
- (instancetype)initWithAlert:(BOOL)showAlert {
    self = [super init];
    if (self) {
        [BGSetting getBgSettingUpdate:showAlert maintain:showAlert eventBack:nil];
    }
    return self;
}
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
     self.navigationController.navigationBarHidden = YES;
    
}
- (void)onTotalUnreadMessageCountChanged:(UInt64)totalUnreadCount {
    [self getUnreadCound];
}
-(void)getUnreadCound {
    __block NSInteger  unRead = 0;
    [[YBImManager shareInstance]getAllUnredNumExceptUser:@[@"dsp_user_"] complete:^(int allUnread) {
        unRead = allUnread;
        dispatch_async(dispatch_get_main_queue(), ^{
            [PublicObj setTabbarBadgeValue:(int)unRead];
        });
        
    }];
    
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.delegate = self;
    [[V2TIMManager sharedInstance] addConversationListener:self];
    
    navArr = [NSMutableArray array];

    _homeVC = [[YBHomeViewController alloc]init];
    YBMsgC2CListVC *msgVC = [[YBMsgC2CListVC alloc]init];
//    NearbyVC *att = [[NearbyVC alloc] init];
    WYTCityPageVC *att = [[WYTCityPageVC alloc]init];
    YBCenterVC *userInfo = [[YBCenterVC alloc]init];
    userInfo.isTabbar = YES;
    NSString *locCity = YZMsg(@"同城");
    if ([CityDefault getLocationCity]) {
        locCity = [CityDefault getLocationCity];
        if ([locCity hasSuffix:@"市"]) {
            locCity = [locCity substringToIndex:locCity.length-1];
        }
    }
    NSMutableArray *arr = [NSMutableArray arrayWithArray:@[_homeVC,att,msgVC,userInfo]];
    for (int i = 0 ; i<arr.count; i++) {
        YBNavigationController *nav = [[YBNavigationController alloc]initWithRootViewController:arr[i]];
        [self addChildViewController:nav];

    }
    self.viewControllers = arr;
    Class SysTabBtn = NSClassFromString(@"UITabBarButton");
    for (UIView *subView in self.tabBar.subviews) {
        if ([subView isKindOfClass:SysTabBtn]) {
            subView.hidden = YES;
        }
    }
    [self.tabBar insertSubview:self.tabbar atIndex:3];
    
    [[UITabBar appearance]setShadowImage:[UIImage new]];
    [[UITabBar appearance]setBackgroundImage:[UIImage new]];
}

//- (BOOL)tabBarController:(UITabBarController *)tabBarController shouldSelectViewController:(UIViewController *)viewController {
//    if (![[[viewController.childViewControllers firstObject] class] isEqual:[YBHomeViewController class]] &&
//        ![[[viewController.childViewControllers firstObject] class] isEqual:[NearbyVC class]]) {
//        NSLog(@"uid是%@",[Config getOwnID]);
//        if ([[Config getOwnID] intValue] <= 0) {
//            [PublicObj warnLogin];
//            return NO;
//        }else{
//            return YES;
//        }
//    }else{
//        //rk_1-30
//        if ([tabBarController.selectedViewController isEqual:[tabBarController.viewControllers firstObject]]) {
//            //! 即将选中的页面是之前上一次选中的控制器页面
//            if (![viewController isEqual:tabBarController.selectedViewController]) {
//                return YES;
//            }
//            //获取当前点击时间
//            NSDate *currentDate = [NSDate date];
//            CGFloat timeInterval = currentDate.timeIntervalSince1970 - _lastSelectedDate.timeIntervalSince1970;
//            // 两次点击时间间隔少于 0.5S 视为一次双击
//            if (timeInterval < 0.5) {
//                // 通知首页刷新数据
//                [[NSNotificationCenter defaultCenter]postNotificationName:DoubleClickRefreshNot object:nil];
//                // 双击之后将上次选中时间置为1970年0点0时0分0秒,用以避免连续三次或多次点击
//                _lastSelectedDate = [NSDate dateWithTimeIntervalSince1970:0];
//                return NO;
//            }
//            // 若是单击将当前点击时间复制给上一次单击时间
//            _lastSelectedDate = currentDate;
//
//        }
//
//        return YES;
//    }
//}

#pragma mark - <RTabBarDelegate>
- (void)tabbar:(RTabBar *)tabbar withBtn:(TabBarType)tabbarType
{
    
//    if ([[Config getOwnID] intValue]<=0 && [Config getTranslate]) {
//        return;
//    }
    if (tabbarType !=TabBarTypeAdd){
        self.selectedIndex = tabbarType-TabBarTypeHome;
        
        if(tabbarType == TabBarTypeMe || tabbarType == TabBarTypeNews){
            if ([[Config getOwnID] intValue] <= 0) {
                [PublicObj resetVC:[[YBTabBarController alloc]initWithAlert:NO]];

                [PublicObj warnLogin];
                [[NSNotificationCenter defaultCenter]postNotificationName:@"changTabBarColor" object:@"1"];
                return;
            } else{
                [[NSNotificationCenter defaultCenter]postNotificationName:@"changTabBarColor" object:@"1"];
            }
        }else{
            [[NSNotificationCenter defaultCenter]postNotificationName:@"changTabBarColor" object:@"0"];
        }

        if(tabbarType == TabBarTypeHome){
            //获取当前点击时间
            NSDate *currentDate = [NSDate date];
            CGFloat timeInterval = currentDate.timeIntervalSince1970 - _lastSelectedDate.timeIntervalSince1970;
            // 两次点击时间间隔少于 0.5S 视为一次双击
            if (timeInterval < 0.5) {
                // 通知首页刷新数据
                [[NSNotificationCenter defaultCenter]postNotificationName:DoubleClickRefreshNot object:nil];
                // 双击之后将上次选中时间置为1970年0点0时0分0秒,用以避免连续三次或多次点击
                _lastSelectedDate = [NSDate dateWithTimeIntervalSince1970:0];
                return ;
            }
            // 若是单击将当前点击时间复制给上一次单击时间
            _lastSelectedDate = currentDate;

        }
        if (tabbarType == TabBarTypeAddress) {
            //获取当前点击时间
            NSDate *currentDate = [NSDate date];
            CGFloat timeInterval = currentDate.timeIntervalSince1970 - _cityLastDate.timeIntervalSince1970;
            // 两次点击时间间隔少于 0.5S 视为一次双击
            if (timeInterval < 0.5) {
                // 通知首页刷新数据
                [[NSNotificationCenter defaultCenter]postNotificationName:CityDoubleClick object:nil];
                // 双击之后将上次选中时间置为1970年0点0时0分0秒,用以避免连续三次或多次点击
                _cityLastDate = [NSDate dateWithTimeIntervalSince1970:0];
                return ;
            }
            // 若是单击将当前点击时间复制给上一次单击时间
            _cityLastDate = currentDate;
        }
        
        return;
    }
    /// 点击了中间的相机
    [self centerBtnDidClicked];
}
#pragma mark getting
- (RTabBar *)tabbar
{
    if (!_tabbar) {
        _tabbar = [[RTabBar alloc] initWithFrame:CGRectMake(0, 0, _window_width, tabBarHeight)];
        _tabbar.delegate = self;
        UIApplication *app =[UIApplication sharedApplication];
        AppDelegate *app2 = (AppDelegate*)app.delegate;
        app2.rtabbar = _tabbar;

    }
    return _tabbar;
}

//- (BOOL)tabBarController:(UITabBarController *)tabBarController shouldSelectViewController:(UIViewController *)viewController {
//    if ([[Config getOwnID] intValue]<=0 && [Config getTranslate]) {
//        return NO;
//    }
//
//    if (![[[viewController.childViewControllers firstObject] class] isEqual:[YBHomeViewController class]] &&
//        ![[[viewController.childViewControllers firstObject] class] isEqual:[NearbyVC class]]) {
//        NSLog(@"uid是%@",[Config getOwnID]);
//        if ([[Config getOwnID] intValue] <= 0) {
//            [PublicObj warnLogin];
//            return NO;
//        }else{
//            return YES;
//        }
//    }else{
//        //rk_1-30
//        if ([tabBarController.selectedViewController isEqual:[tabBarController.viewControllers firstObject]]) {
//            //! 即将选中的页面是之前上一次选中的控制器页面
//            if (![viewController isEqual:tabBarController.selectedViewController]) {
//                return YES;
//            }
//            //获取当前点击时间
//            NSDate *currentDate = [NSDate date];
//            CGFloat timeInterval = currentDate.timeIntervalSince1970 - _lastSelectedDate.timeIntervalSince1970;
//            // 两次点击时间间隔少于 0.5S 视为一次双击
//            if (timeInterval < 0.5) {
//                // 通知首页刷新数据
//                [[NSNotificationCenter defaultCenter]postNotificationName:DoubleClickRefreshNot object:nil];
//                // 双击之后将上次选中时间置为1970年0点0时0分0秒,用以避免连续三次或多次点击
//                _lastSelectedDate = [NSDate dateWithTimeIntervalSince1970:0];
//                return NO;
//            }
//            // 若是单击将当前点击时间复制给上一次单击时间
//            _lastSelectedDate = currentDate;
//
//        }
//
//        return YES;
//    }
//}

/**
 * 中间按钮（预留）
 */
-(void)centerBtnDidClicked {
//    if ([[Config getOwnID] intValue]<=0 && [Config getTranslate]) {
//        return;
//    }

    if ([[Config getOwnID] intValue] <= 0) {
        //说明是游客
        [PublicObj warnLogin];
        return;
    }
    AppDelegate *app = (AppDelegate *)[UIApplication sharedApplication].delegate;
    if (0 < app.allUploadPro && app.allUploadPro < 1) {
        [MBProgressHUD showPop:YZMsg(@"视频发布中，暂不支持操作")];
        return;
    }
    
    if ([YBYoungManager shareInstance].youngSwitch == 1) {
        [MBProgressHUD showError:YZMsg(@"青少年模式下不支持该功能")];
        return;
    }
    
    //rk_test
//    TCVideoPublishController *ssss = [[TCVideoPublishController alloc]init];
//    [[YBBaseAppDelegate sharedAppDelegate] pushViewController:ssss animated:YES];
//    return;
    
    BOOL mediaAccess =  [[RKSysAccess shareInstance] checkMediaAccess];
    if (mediaAccess == NO) {
        YBWeakSelf;
        [[RKSysAccess shareInstance] requestMediaAccess:^(BOOL access) {
            if (access) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    [weakSelf requesetStatus];
                });
            }
        }];
    }else{
        [self requesetStatus];
    }
}

-(void)requesetStatus {
    YBWeakSelf;
    [MBProgressHUD showMessage:@""];
    //wyt_vip
    [WYNetworking postWithUrl:@"User.checkLiveVipStatus" Dic:nil Suc:^(int code, id info, NSString *msg) {
        [MBProgressHUD hideHUD];
        if (code == 0) {
            //获取美狐预存值
            [sproutCommon getMHValueFromService];
            
            NSDictionary *dic = [info firstObject];
            [YBPower saveUnified:dic];
            [YBLiveOrVideo showLiveOrVideoSel];
        }else if(code == 1001){
            [weakSelf showAlertMsg:msg];
        }else{
            [MBProgressHUD showPop:msg];
        }
    } Fail:^(id fail) {
        [MBProgressHUD hideHUD];
    }];
}

-(void)showAlertMsg:(NSString *)alertMsg; {
    NSDictionary *contentDic = @{@"title":@"",
                                @"msg":alertMsg,
                                @"left":YZMsg(@"取消"),
                                 @"right":YZMsg(@"去认证")};
    [YBAlertView showAlertView:contentDic complete:^(int eventType) {
        if (eventType == 1) {
            dispatch_async(dispatch_get_main_queue(), ^{
                /*
                NSString *url = [NSString stringWithFormat:@"%@/Appapi/Auth/index?uid=%@&token=%@",h5url,[Config getOwnID],[Config getOwnToken]];;
                PubH5 *h5VC = [[PubH5 alloc]init];
                h5VC.url = url;
                [[YBBaseAppDelegate sharedAppDelegate]pushViewController:h5VC animated:YES];
                */
                YBUserAuthVC *authVC = [[YBUserAuthVC alloc]init];
                [[YBBaseAppDelegate sharedAppDelegate]pushViewController:authVC animated:YES];
            });
        }
    }];
}

/**
 *  初始化控制器
// */
//- (void)setChildViewController:(UIViewController*)childVC Title:(NSString*)title Image:(NSString *)image SelectedImage:(NSString *)selectedImage {
//    /**
//     *  添加 tabBarItem 上的文字和图片
//     */
//    childVC.tabBarItem.title=title;
////    childVC.tabBarItem.image=[[UIImage imageNamed:@""]imageWithRenderingMode:UIImageRenderingModeAutomatic];;
////    childVC.tabBarItem.selectedImage=[[UIImage imageNamed:@""]imageWithRenderingMode:UIImageRenderingModeAutomatic];
//    YBNavigationController *nav = [[YBNavigationController alloc]initWithRootViewController:childVC];
////    nav.tabBarItem.imageInsets = UIEdgeInsetsMake(6, 0, -6, 0);
////    nav.tabBarItem.titlePositionAdjustment = UIOffsetMake(0, -3);
//    [self addChildViewController:nav];
////    [nav didMoveToParentViewController:self];
//}
////背景色
//-(UIImage *)drawTabBarItemBckgroundImageWithSize:(CGSize)size {
//    UIGraphicsBeginImageContext(size);
//    CGContextRef ctx = UIGraphicsGetCurrentContext();
//    CGContextSetRGBFillColor(ctx, 29.0/255, 30.0/255, 39.0/255, 1);
//    CGContextFillRect(ctx, CGRectMake(0, 0, size.width, size.height));
//    UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
//    UIGraphicsEndImageContext();
//    return img;
//}
//重写
-(void)setNeedsStatusBarAppearanceUpdate {
    [super setNeedsStatusBarAppearanceUpdate];
    
    //选中背景色
    //CGSize indicatorImageSize = CGSizeMake(self.tabBar.bounds.size.width/4, self.tabBar.bounds.size.height);
    //self.tabBar.selectionIndicatorImage = [self drawTabBarItemBckgroundImageWithSize:indicatorImageSize];
}

- (void)selectController:(NSInteger)index{
    self.selectedIndex=index;
    _tabbar.selectIndex = index;
}
-(void)goForYouViewRefresh:(BOOL)refresh {
    [_homeVC scrollToIdx:0 refresh:refresh];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



@end
